import asyncio


async def waiter_task(name: str, cond):
    count: int = 0
    while True:
        print(f"{name} waiting...")
        # 等待协程事件
        async with cond:
            await cond.wait()
            print(f"{name} event.wait() ok,,, {count}")
            count += 1

condition_flag = False
async def waiter_for_task(name: str, cond):
    global condition_flag
    count: int = 0
    while True:
        print(f"{name} waiting...")
        # 等待协程事件
        async with cond:
            await cond.wait_for(lambda: condition_flag)
            print(f"{name} event.wait() ok,,, {count}")
            count += 1
            condition_flag = False

async def cmd_control(cond):
    help="""输入命令:
1: notify 通知一个
2: notify_all 通知所有
3: 设置condition_flag = True, 通知所有
"""
    global condition_flag
    while True:
        cmd = input(help)
        await cond.acquire()
        try:
            if cmd == "1":
                cond.notify()
            elif cmd == "2":
                cond.notify_all()
            elif cmd == "3":
                condition_flag = True
                cond.notify_all()
            else:
                print("未知命令")
        finally:
            cond.release()
        await asyncio.sleep(1)


async def main():
    cond = asyncio.Condition()
    await asyncio.gather(
        waiter_task("taskA", cond),
        waiter_task("taskB", cond),
        waiter_for_task("taskC", cond),
        cmd_control(cond),
    )


if __name__ == "__main__":
    asyncio.run(main())
